function render(data) {
    let userErr = $(".reg-box .userErr");
    if (data.code == 0) {
        alert(data.msp);
    } else if (data.code == 2) {
        userErr.innerHTML = data.msp;
    } else {
        alert(data.msp);
    }
}

function reg() {
    let user = $(".reg-box .user");
    let pw = $(".reg-box .pw");
    let userErr = $(".reg-box .userErr");
    let pwErr = $('.reg-box .pwErr');
    let regBtn = $(".reg-box .regBtn");

    regBtn.onclick = function(e) {
        e.preventDefault();
        let userVal = user.value;
        let pwVal = pw.value;


        // 检测有效性
        if (!/^[a-z]\w{5,11}$/i.test(userVal)) {
            userErr.innerHTML = '用户名必须是6-12位字母数字下划线，首字符必须是字母';
            return;
        } else {
            userErr.innerHTML = '';
        }
        if (!/^[a-z\d]{6,8}$/i.test(pwVal)) {
            pwErr.innerHTML = '密码必须是6-8位字母数字';
            return;
        } else {
            pwErr.innerHTML = " ";
        }

        let url = `./api/reg1.php?user=${userVal}&pw=${pwVal}`;
        ajax(url, render);
    }
}

function loginRender(data) {
    // console.log(data);
    let userErr = $(".login-box .userErr");
    let pwErr = $(".login-box .pwErr");

    if (data.code == 0) {
        location.href = "./success";
    } else if (data.code == 1) {
        pwErr.innerHTML = data.msp;
    } else {
        userErr.innerHTML = data.msp;
    }
}

function login() {
    let user = $(".login-box .user");
    let pw = $(".login-box .pw");
    let userErr = $(".login-box .userErr");
    let pwErr = $('.login-box .pwErr');
    let loginBtn = $(".login-box .loginBtn");

    loginBtn.onclick = function(e) {
        e.preventDefault();
        let userVal = user.value;
        let pwVal = pw.value;


        // 检测有效性
        if (!/^[a-z]\w{5,11}$/i.test(userVal)) {
            userErr.innerHTML = '用户名必须是6-12位字母数字下划线，首字符必须是字母';
            return;
        } else {
            userErr.innerHTML = '';
        }
        if (!/^[a-z\d]{6,8}$/i.test(pwVal)) {
            pwErr.innerHTML = '密码必须是6-8位字母数字';
            return;
        } else {
            pwErr.innerHTML = " ";
        }

        let url = `./api/login1.php?user=${userVal}&pw=${pwVal}`;
        ajax(url, loginRender);
    }
}
reg();
login();